<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Hexo, NexT" />








  <link rel="shortcut icon" type="image/x-icon" href="/blog/favicon.ico?v=5.1.2" />






<meta name="description" content="1. 什么是 Promise1.1. 定义 Promise 对象用于异步计算 一个 Promise 表示一个现在、将来或永不可能用到的值  1.2. 优缺点1.2.1. 优点 可以将异步操作以同步操作的流程表达出来，避免了层层嵌套的回调函数 Promise 对象提供统一的接口，使得控制异步操作更加容易  1.2.2. 缺点 无法取消 Promise，一旦新建它就会立即执行，无法中途取消。 如果不设">
<meta property="og:type" content="article">
<meta property="og:title" content="ECMAScript6 之 Promise™">
<meta property="og:url" content="http://xiezixi.oschina.io/2018/06/07/ES6-Promise/index.html">
<meta property="og:site_name" content="个人博客">
<meta property="og:description" content="1. 什么是 Promise1.1. 定义 Promise 对象用于异步计算 一个 Promise 表示一个现在、将来或永不可能用到的值  1.2. 优缺点1.2.1. 优点 可以将异步操作以同步操作的流程表达出来，避免了层层嵌套的回调函数 Promise 对象提供统一的接口，使得控制异步操作更加容易  1.2.2. 缺点 无法取消 Promise，一旦新建它就会立即执行，无法中途取消。 如果不设">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://xiezixi.oschina.io/blog/images/promise1.png">
<meta property="og:updated_time" content="2018-06-07T12:58:45.833Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="ECMAScript6 之 Promise™">
<meta name="twitter:description" content="1. 什么是 Promise1.1. 定义 Promise 对象用于异步计算 一个 Promise 表示一个现在、将来或永不可能用到的值  1.2. 优缺点1.2.1. 优点 可以将异步操作以同步操作的流程表达出来，避免了层层嵌套的回调函数 Promise 对象提供统一的接口，使得控制异步操作更加容易  1.2.2. 缺点 无法取消 Promise，一旦新建它就会立即执行，无法中途取消。 如果不设">
<meta name="twitter:image" content="http://xiezixi.oschina.io/blog/images/promise1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Muse',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://xiezixi.oschina.io/2018/06/07/ES6-Promise/"/>





  <title>ECMAScript6 之 Promise™ | 个人博客</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">曦瓜皮</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>


 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://xiezixi.oschina.io/blog/2018/06/07/ES6-Promise/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="曦瓜皮">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="个人博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">ECMAScript6 之 Promise™</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-06-07T20:58:45+08:00">
                2018-06-07
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/ECMAScript6/" itemprop="url" rel="index">
                    <span itemprop="name">ECMAScript6</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="1-什么是-Promise"><a href="#1-什么是-Promise" class="headerlink" title="1. 什么是 Promise"></a>1. 什么是 Promise</h2><h3 id="1-1-定义"><a href="#1-1-定义" class="headerlink" title="1.1. 定义"></a>1.1. 定义</h3><ul>
<li>Promise 对象用于异步计算</li>
<li>一个 Promise 表示一个现在、将来或永不可能用到的值</li>
</ul>
<h3 id="1-2-优缺点"><a href="#1-2-优缺点" class="headerlink" title="1.2. 优缺点"></a>1.2. 优缺点</h3><h4 id="1-2-1-优点"><a href="#1-2-1-优点" class="headerlink" title="1.2.1. 优点"></a>1.2.1. 优点</h4><ul>
<li>可以将异步操作以同步操作的流程表达出来，避免了层层嵌套的回调函数</li>
<li>Promise 对象提供统一的接口，使得控制异步操作更加容易</li>
</ul>
<h4 id="1-2-2-缺点"><a href="#1-2-2-缺点" class="headerlink" title="1.2.2. 缺点"></a>1.2.2. 缺点</h4><ul>
<li>无法取消 Promise，一旦新建它就会立即执行，无法中途取消。</li>
<li>如果不设置回调函数，Promise 内部抛出的错误，不会反应到外部</li>
<li>当处于 Pending 状态时，无法得知目前进展到哪一个阶段</li>
</ul>
<h3 id="1-3-使用方法"><a href="#1-3-使用方法" class="headerlink" title="1.3. 使用方法"></a>1.3. 使用方法</h3><p>Promise 构造函数包含一个参数和一个带有 resolve（解析）和 reject（拒绝）两个参数的回调。在回调中执行一些操作（例如异步），如果一切都正常，则调用 resolve，否则调用 reject。</p>
<ul>
<li>Promise 状态发生变化，就会触发 <code>.then()</code> 里的响应函数处理后续步骤</li>
<li>Promise 状态最多只能改变一次，一经改变，不能再变<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="built_in">Promise</span>(</span><br><span class="line">    <span class="comment">// 执行器 executor</span></span><br><span class="line">    <span class="function"><span class="keyword">function</span> (<span class="params">resolve, reject</span>) </span>&#123;</span><br><span class="line">        <span class="comment">// 一段耗时很长的异步操作</span></span><br><span class="line"></span><br><span class="line">        resolve(); <span class="comment">// 数据处理完成</span></span><br><span class="line"></span><br><span class="line">        reject(); <span class="comment">// 数据处理出错</span></span><br><span class="line">    &#125;</span><br><span class="line">).then(<span class="function"><span class="keyword">function</span> <span class="title">A</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 处理成功 下一步操作</span></span><br><span class="line">&#125;, <span class="function"><span class="keyword">function</span> <span class="title">B</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 处理失败 下一步操作</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p><img src="http://xiezixi.oschina.io/blog/images/promise1.png" alt="promise"></p>
<h3 id="1-4-Promise-的-3-种状态"><a href="#1-4-Promise-的-3-种状态" class="headerlink" title="1.4. Promise 的 3 种状态"></a>1.4. Promise 的 3 种状态</h3><table>
<thead>
<tr>
<th>状态</th>
<th>含义</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>pending</code></td>
<td>待定</td>
<td>初始状态</td>
</tr>
<tr>
<td><code>fulfilled</code></td>
<td>实现</td>
<td>操作成功</td>
</tr>
<tr>
<td><code>rejected</code></td>
<td>被否决</td>
<td>操作失败</td>
</tr>
</tbody>
</table>
<h3 id="1-5-最简单的实例"><a href="#1-5-最简单的实例" class="headerlink" title="1.5. 最简单的实例"></a>1.5. 最简单的实例</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 先输出 here we go，等待 2s 后输出 hello world</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'here we go'</span>);</span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="params">resolve</span> =&gt;</span> &#123;</span><br><span class="line">    setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        resolve(<span class="string">'hello'</span>);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;).then(<span class="function"><span class="params">value</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(value + <span class="string">' world'</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h3 id="1-6-使用-Promise-实现-Ajax"><a href="#1-6-使用-Promise-实现-Ajax" class="headerlink" title="1.6. 使用 Promise 实现 Ajax"></a>1.6. 使用 Promise 实现 Ajax</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">ajax</span>(<span class="params">URL</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span> (<span class="params">resolve, reject</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> req = <span class="keyword">new</span> XMLHttpRequest();</span><br><span class="line">        req.open(<span class="string">'GET'</span>, URL, <span class="literal">true</span>);</span><br><span class="line">        req.onload = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">            <span class="keyword">if</span> (req.status === <span class="number">200</span>) &#123;</span><br><span class="line">                resolve(req.responseText);</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                reject(<span class="keyword">new</span> <span class="built_in">Error</span>(req.statusText));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        req.onerror = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">            reject(<span class="keyword">new</span> <span class="built_in">Error</span>(req.statusText));</span><br><span class="line">        &#125;;</span><br><span class="line">        req.send();</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="1-7-浏览器兼容性"><a href="#1-7-浏览器兼容性" class="headerlink" title="1.7. 浏览器兼容性"></a>1.7. 浏览器兼容性</h3><p><a href="https://caniuse.com/#search=Promise" target="_blank" rel="noopener">Promise 浏览器兼容性</a></p>
<h2 id="2-异步的问题"><a href="#2-异步的问题" class="headerlink" title="2. 异步的问题"></a>2. 异步的问题</h2><h3 id="2-1-异步操作的常见语法"><a href="#2-1-异步操作的常见语法" class="headerlink" title="2.1. 异步操作的常见语法"></a>2.1. 异步操作的常见语法</h3><ol>
<li><p>事件的侦听与响应</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">start</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 响应事件，进行对应的操作</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// JavaScript</span></span><br><span class="line"><span class="built_in">document</span>.getElementById(<span class="string">'start'</span>).addEventListener(<span class="string">'click'</span>, start, <span class="literal">false</span>);</span><br><span class="line"><span class="comment">// jQuery</span></span><br><span class="line">$(<span class="string">"#start"</span>).on(<span class="string">'click'</span>, start);</span><br></pre></td></tr></table></figure>
</li>
<li><p>回调</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// ajax</span></span><br><span class="line">$.ajax(&#123;</span><br><span class="line">    url: <span class="string">'https://baidu.com'</span>,</span><br><span class="line">    success: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">        <span class="comment">// 回调函数</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// 页面加载完毕之后回调</span></span><br><span class="line">$(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 回调函数</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h3 id="2-2-异步回调的问题"><a href="#2-2-异步回调的问题" class="headerlink" title="2.2. 异步回调的问题"></a>2.2. 异步回调的问题</h3><ul>
<li>嵌套层次很深，难以维护<br>回调地狱<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">a(<span class="function"><span class="keyword">function</span> (<span class="params">arg1</span>) </span>&#123;</span><br><span class="line">    b(arg1,<span class="function"><span class="keyword">function</span> (<span class="params">arg2</span>) </span>&#123;</span><br><span class="line">        c(arg2,<span class="function"><span class="keyword">function</span> (<span class="params">arg3</span>) </span>&#123;</span><br><span class="line">            d(arg3,<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">                <span class="comment">// 回调地狱</span></span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
</li>
</ul>
<ol start="2">
<li>无法正常的使用 return 和 throw<br>不能捕获异步函数的异常，因为异步函数是在不同的栈里面运行，没办法正常的使用 try catch 处理异步函数中的错误。</li>
<li>无法正常检索堆栈信息<br>每次回调都是在系统层面的一个新的堆栈</li>
<li>多个回调之间难以建立联系<br>一个回调一旦启动，我们再也没有办法对它操作</li>
</ol>
<h2 id="3-使用-Promise"><a href="#3-使用-Promise" class="headerlink" title="3. 使用 Promise"></a>3. 使用 Promise</h2><h3 id="3-1-两步执行"><a href="#3-1-两步执行" class="headerlink" title="3.1. 两步执行"></a>3.1. 两步执行</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 隔 2s 后输出 hello world，再隔 2s 后输出 hello promise</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'here we go'</span>);</span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="params">resolve</span> =&gt;</span> &#123;</span><br><span class="line">    setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        resolve(<span class="string">'hello'</span>);</span><br><span class="line">    &#125;,<span class="number">2000</span>);</span><br><span class="line">&#125;).then(<span class="function"><span class="params">value</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(value + <span class="string">' world'</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="params">resolve</span> =&gt;</span> &#123;</span><br><span class="line">       setTimeout(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">           resolve(<span class="string">'hello promise'</span>);</span><br><span class="line">       &#125;,<span class="number">2000</span>);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;).then(<span class="function"><span class="params">value</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(value);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h3 id="3-2-then"><a href="#3-2-then" class="headerlink" title="3.2. .then()"></a>3.2. .then()</h3><ul>
<li><code>.then()</code> 接收两个函数作为参数，分别代表 <code>fulfilled</code> 和 <code>rejected</code></li>
<li><code>.then()</code> 返回一个新的 Promise 实例，所以它可以链式调用</li>
<li>当前面的 Promise 状态改变时，<code>.then()</code> 根据其最终状态，选择特定的状态响应函数执行</li>
<li>状态响应函数可以返回新的 Promise，或者其它值；如果返回其它值，则会立刻执行下一级 <code>.then()</code></li>
<li>如果返回新的 Promise，那么下一级 <code>.then()</code> 会在新 Promise 状态改变之后执行</li>
</ul>
<h3 id="3-3-错误处理"><a href="#3-3-错误处理" class="headerlink" title="3.3. 错误处理"></a>3.3. 错误处理</h3><p>Promise 会自动捕获内部异常，并交给 rejected 响应函数处理。强烈建议在所有队列最后都加上 <code>.catch()</code>，以避免漏掉错误处理造成意想不到的问题。<br><strong>处理错误的两种方法</strong></p>
<ul>
<li>rejected(‘错误信息’)        .then(null, message =&gt; {});</li>
<li>throw new Error(‘错误信息’) .catch(message =&gt; {});</li>
</ul>
<p>推荐使用 catch 捕获异常，更加清晰好读，并且可以捕获前端的错误。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="string">'here we go'</span>);</span><br><span class="line"><span class="keyword">var</span> promise = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve,reject</span>) =&gt;</span> &#123;</span><br><span class="line">    reject(<span class="string">'错误'</span>); <span class="comment">// throw new Error('错误');</span></span><br><span class="line">&#125;);</span><br><span class="line">promise.then(<span class="function"><span class="params">value</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(value);</span><br><span class="line">    <span class="keyword">return</span> value;</span><br><span class="line">&#125;).catch(<span class="function"><span class="params">value</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"catch:"</span> + value);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h2 id="4-Promise-常用函数"><a href="#4-Promise-常用函数" class="headerlink" title="4. Promise 常用函数"></a>4. Promise 常用函数</h2><h3 id="4-1-Promise-all"><a href="#4-1-Promise-all" class="headerlink" title="4.1. Promise.all()"></a>4.1. Promise.all()</h3><p>Promise.all 方法用于将多个 Promise 实例，包装成一个新的 Promise 实例。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Promise</span>.all([p1, p2, p3]);</span><br></pre></td></tr></table></figure></p>
<p>上面代码中，Promise.all 方法接受一个数组作为参数，p1、p2、p3 都是 Promise 对象的实例。（Promise.all 方法的参数不一定是数组，但是必须具有 iterator 接口，且返回的每个成员都是 Promise 实例。）<br>p 的状态由 p1、p2、p3 决定，分成两种情况:</p>
<ol>
<li>只有 p1、p2、p3 的状态都变成 fulfilled，p的状态才会变成 fulfilled，此时 p1、p2、p3 的返回值组成一个数组，传递给 p 的回调函数</li>
<li>只要 p1、p2、p3 之中有一个被 rejected，p的状态就变成 rejected，此时第一个被 reject 的实例的返回值，会传递给 p 的回调函数</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">console.log(&apos;here we go&apos;);</span><br><span class="line">Promise.all([1, 2, 3])</span><br><span class="line">    .then(all =&gt; &#123;</span><br><span class="line">        console.log(&quot;1: &quot; + all);</span><br><span class="line">        let promise1 = new Promise(resolve =&gt; &#123;</span><br><span class="line">            resolve(&apos;hello&apos;);</span><br><span class="line">        &#125;);</span><br><span class="line">        let promise2 = new Promise(resolve =&gt; &#123;</span><br><span class="line">            resolve(&apos;world&apos;);</span><br><span class="line">        &#125;);</span><br><span class="line">        return Promise.all([promise1, promise2]);</span><br><span class="line">    &#125;)</span><br><span class="line">    .then(all =&gt; &#123;</span><br><span class="line">        console.log(&quot;2: &quot; + all);</span><br><span class="line">        let promise3 = new Promise((resolve, reject) =&gt; &#123;</span><br><span class="line">            reject(&apos;错误-promise3&apos;);</span><br><span class="line">        &#125;);</span><br><span class="line">        let promise4 = new Promise((resolve, reject) =&gt; &#123;</span><br><span class="line">            reject(&apos;错误-promise4&apos;);</span><br><span class="line">        &#125;);</span><br><span class="line">        return Promise.all([promise3, promise4]);</span><br><span class="line">    &#125;).then(all =&gt; &#123;</span><br><span class="line">        console.log(all);</span><br><span class="line">    &#125;)</span><br><span class="line">    .catch(err =&gt; &#123;</span><br><span class="line">        console.log(&apos;catch: &apos; + err);</span><br><span class="line">    &#125;);</span><br></pre></td></tr></table></figure>
<h3 id="4-2-Promise-race"><a href="#4-2-Promise-race" class="headerlink" title="4.2. Promise.race()"></a>4.2. Promise.race()</h3><p>Promise.race 方法同样是将多个 Promise 实例，包装成一个新的 Promise 实例。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> p = <span class="built_in">Promise</span>.race([p1, p2, p3]);</span><br></pre></td></tr></table></figure></p>
<p>上面代码中，只要 p1、p2、p3 之中有一个实例率先改变状态，p 的状态就跟着改变。那个率先改变的 Promise 实例的返回值，就传递给p的返回值。<br>如果 Promise.all 方法和 Promise.race 方法的参数，不是 Promise 实例，就会先调用下面讲到的 Promise.resolve 方法，将参数转为 Promise 实例，再进一步处理。</p>
<h3 id="4-3-Promise-resolve"><a href="#4-3-Promise-resolve" class="headerlink" title="4.3. Promise.resolve()"></a>4.3. Promise.resolve()</h3><p>有时需要将现有对象转为 Promise 对象，<code>Promise.resolve()</code> 方法就起到这个作用。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> jsPromise = <span class="built_in">Promise</span>.resolve($.ajax(<span class="string">'/whatever.json'</span>));</span><br></pre></td></tr></table></figure></p>
<p>上面代码将 jQuery 生成 deferred 对象，转为一个新的 ES6 的 Promise 对象。<br>如果 <code>Promise.resolve()</code> 方法的参数，不是具有 <code>then</code> 方法的对象（又称 <code>thenable 对象</code>），则返回一个新的 Promise 对象，且它的状态为 fulfilled。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> p = <span class="built_in">Promise</span>.resolve(<span class="string">'Hello'</span>);</span><br><span class="line"></span><br><span class="line">p.then(<span class="function"><span class="keyword">function</span> (<span class="params">s</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(s); <span class="comment">// Hello</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure></p>
<p>上面代码生成一个新的 Promise 对象的实例 p，它的状态为 fulfilled，所以回调函数会立即执行，<code>Promise.resolve()</code> 方法的参数就是回调函数的参数。<br>如果 <code>Promise.resolve()</code> 方法的参数是一个 Promise 对象的实例，则会被原封不动地返回。</p>
<h3 id="4-4-Promise-reject"><a href="#4-4-Promise-reject" class="headerlink" title="4.4. Promise.reject()"></a>4.4. Promise.reject()</h3><p><code>Promise.reject()</code> 方法也会返回一个新的 Promise 实例，该实例的状态为 rejected。<code>Promise.reject()</code> 方法的参数会被传递给实例的回调函数。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> p = <span class="built_in">Promise</span>.reject(<span class="string">'出错了'</span>);</span><br><span class="line"></span><br><span class="line">p.then(<span class="literal">null</span>, <span class="function"><span class="keyword">function</span> (<span class="params">s</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(s); <span class="comment">// 出错了</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure></p>
<p>上面代码生成一个 Promise 对象的实例 p，状态为 rejected，回调函数会立即执行。</p>
<h2 id="5-兼容性说明"><a href="#5-兼容性说明" class="headerlink" title="5. 兼容性说明"></a>5. 兼容性说明</h2><p>如果需要在 IE 中使用 Promise，方法有两种：</p>
<ul>
<li>只实现异步队列<br><a href="http://api.jquery.com/category/deferred-object/" target="_blank" rel="noopener">jQuery.defered</a></li>
<li>兼容所有平台<br><a href="https://github.com/petkaantonov/bluebird" target="_blank" rel="noopener">Bluebird</a><br><a href="https://github.com/taylorhakes/promise-polyfill" target="_blank" rel="noopener">Promise polyfill</a></li>
</ul>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/06/07/JS-常用设计模式/" rel="next" title="JavaScript 之常用设计模式">
                <i class="fa fa-chevron-left"></i> JavaScript 之常用设计模式
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/blog/images/avatar.jpg"
               alt="曦瓜皮" />
          <p class="site-author-name" itemprop="name">曦瓜皮</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/blog/archives/">
                <span class="site-state-item-count">15</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/blog/categories/index.html">
                <span class="site-state-item-count">6</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        

      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-什么是-Promise"><span class="nav-number">1.</span> <span class="nav-text">1. 什么是 Promise</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-定义"><span class="nav-number">1.1.</span> <span class="nav-text">1.1. 定义</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-优缺点"><span class="nav-number">1.2.</span> <span class="nav-text">1.2. 优缺点</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-1-优点"><span class="nav-number">1.2.1.</span> <span class="nav-text">1.2.1. 优点</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-2-缺点"><span class="nav-number">1.2.2.</span> <span class="nav-text">1.2.2. 缺点</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-使用方法"><span class="nav-number">1.3.</span> <span class="nav-text">1.3. 使用方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-4-Promise-的-3-种状态"><span class="nav-number">1.4.</span> <span class="nav-text">1.4. Promise 的 3 种状态</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-5-最简单的实例"><span class="nav-number">1.5.</span> <span class="nav-text">1.5. 最简单的实例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-6-使用-Promise-实现-Ajax"><span class="nav-number">1.6.</span> <span class="nav-text">1.6. 使用 Promise 实现 Ajax</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-7-浏览器兼容性"><span class="nav-number">1.7.</span> <span class="nav-text">1.7. 浏览器兼容性</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-异步的问题"><span class="nav-number">2.</span> <span class="nav-text">2. 异步的问题</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-异步操作的常见语法"><span class="nav-number">2.1.</span> <span class="nav-text">2.1. 异步操作的常见语法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-异步回调的问题"><span class="nav-number">2.2.</span> <span class="nav-text">2.2. 异步回调的问题</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-使用-Promise"><span class="nav-number">3.</span> <span class="nav-text">3. 使用 Promise</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-两步执行"><span class="nav-number">3.1.</span> <span class="nav-text">3.1. 两步执行</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-then"><span class="nav-number">3.2.</span> <span class="nav-text">3.2. .then()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-3-错误处理"><span class="nav-number">3.3.</span> <span class="nav-text">3.3. 错误处理</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-Promise-常用函数"><span class="nav-number">4.</span> <span class="nav-text">4. Promise 常用函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-1-Promise-all"><span class="nav-number">4.1.</span> <span class="nav-text">4.1. Promise.all()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2-Promise-race"><span class="nav-number">4.2.</span> <span class="nav-text">4.2. Promise.race()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-3-Promise-resolve"><span class="nav-number">4.3.</span> <span class="nav-text">4.3. Promise.resolve()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-4-Promise-reject"><span class="nav-number">4.4.</span> <span class="nav-text">4.4. Promise.reject()</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-兼容性说明"><span class="nav-number">5.</span> <span class="nav-text">5. 兼容性说明</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">曦瓜皮</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Muse
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.2"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  






  





  

  

  

  

  

  

</body>
</html>
